package service

import (
	"time"

	"example.com/m/v2/model/mysql"
	"example.com/m/v2/types"
	"gorm.io/gorm"
)

type Poster struct {
	BaseService
	db *gorm.DB
}

func NewPoster(svcCtx *ServiceContext, db *gorm.DB) *Poster {
	res := Poster{db: db, BaseService: BaseService{svcCtx: svcCtx}}
	return &res
}

func (p *Poster) Create(req *types.DesignSaveReq, userId int64) *mysql.Poster {
	poster := mysql.Poster{
		UserId:      userId,
		Data:        req.Data,
		Height:      req.Height,
		TemplateId:  req.TempldateId,
		Title:       req.Title,
		Width:       req.Width,
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
	}
	p.db.Create(&poster)
	return &poster
}

func (p *Poster) GetById(id int64) *mysql.Poster {
	var res mysql.Poster
	p.db.Where("id = ?", id).First(&res)
	return &res
}

func (p *Poster) GetListByPage(req *types.DesignMyReq, userId int64) (*[]types.PosterPageDto, int64) {
	var res *[]types.PosterPageDto
	var total int64
	query := p.db.Model(&mysql.Poster{}).Where("status=?", 1).Where("user_id=?", userId).Order("id desc")

	page := 1
	if req.Page != 0 {
		page = req.Page
	}

	pageSize := 20
	if req.PageSize != 0 {
		pageSize = req.PageSize
	}
	query.Count(&total)
	query.Offset(pageSize * (page - 1)).Limit(pageSize).Find(&res)
	return res, total
}

func (p *Poster) Delete(id int64) {
	p.db.Model(&mysql.Poster{}).Where("id=", id).Update("status", 0).Update("updated_time", time.Now())
}
